package memetic.operators;

import java.util.Random;

import funtions.NGDFitnessFunction;

public class DiversificationNGD {

	private Random randomGenerator= new Random();
	private NGDFitnessFunction fitnessFunction;
	
	private int generateRandomValue(int end){
		return randomGenerator.nextInt(end);
	}
	/**
	 * 
	 */
	public void init(NGDFitnessFunction fitnessFunction){
		this.fitnessFunction=fitnessFunction;
	}
	/**
	 * 
	 * 
	 */
	private int[] suitableIndividual(int [] optIndv) {
		int summaryLength=this.fitnessFunction.calculateTotalLengthInd(optIndv);
		/*Max length defined for the summary
		 * 
		 */
		double iterFit=-1,maxFit=-1;
		int[] iterIndv=new int[optIndv.length];
		int[] optIterIndv=new int[optIndv.length];
		iterIndv=optIndv.clone();
		if(summaryLength>this.fitnessFunction.getMaxExecLength()){
			while(summaryLength>this.fitnessFunction.getMaxExecLength()){
				optIterIndv=optIndv.clone();
				iterFit=-1;
				maxFit=-1;
				for(int w=0;w<optIndv.length;w++){
					if (maxFit==-1&&optIndv[w]==1) {
						optIterIndv[w]=0;
						maxFit=this.fitnessFunction.calculateUnConstFitFunct(optIterIndv);
					}
					if (maxFit>-1&&optIndv[w]==1) {
						iterIndv[w]=0;
						iterFit=this.fitnessFunction.calculateUnConstFitFunct(iterIndv);
						if (iterFit>maxFit) {
							optIterIndv=iterIndv.clone();
						}
						if(iterFit==maxFit&&
								this.fitnessFunction.calculateTotalLengthInd(iterIndv)
								>this.fitnessFunction.calculateTotalLengthInd(optIterIndv)){
							optIterIndv=iterIndv.clone();
						}
					}
				}
				optIndv=optIterIndv.clone();
				summaryLength=this.fitnessFunction.calculateTotalLengthInd(optIndv);
			}
		}
		return optIndv;
	}
	/**
	 * Return a mutated individual given a percentage of genes that want to be mutated, which are activated.
	 * @param int percentage Is a number between 1 and 100
	 */
	public int[] mutation_percent(int [] individual,int percentage){
		int numGens=(int) individual.length*percentage/100;
		int genPos=0;
		for(int i=0;i<numGens;i++){
			genPos=generateRandomValue(individual.length);
			if(individual[genPos]==1)
				individual[genPos]=0;
			else
				individual[genPos]=1;
		}
		individual=suitableIndividual(individual.clone());
		return individual;
	}
}
